
#include "output.h"
#define LOG_TAG "Output"
#include "log.h"

static const char *Space = "    ";

void WriteStrPtr(const char *str)
{
    StringEty strBuf;
    StringSet(&strBuf, str);
    WriteString(&strBuf);
}

void WriteNewLine(int space)
{
    StringEty strBuf;
    StringSet(&strBuf, "\n");
    WriteString(&strBuf);

    StringSet(&strBuf, Space);
    while (space > 0) {
        space--;
        WriteString(&strBuf);
    }
}

void WriteStringMap(StringMap map)
{
    int i;
    for (i = 0; i < map->count; i++) {
        WriteStrPtr(" ");
        WriteString(&map->items[i].key);
        WriteStrPtr("=\"");
        WriteString(&map->items[i].val);
        WriteStrPtr("\"");
    }
}

void WriteXmlItem(XmlItem xml, int space)
{
    // 新增一空行
    WriteNewLine(space);
    // 输出起始标签
    WriteStrPtr("<");
    WriteString(&xml->name);

    // 注释和声明
    if (xml->name.ptr[0] == '!') {
        WriteString(&xml->val);
        if (StringEqualStr(&xml->name, "!--")) {
            WriteStrPtr("-->");
        } else {
            WriteStrPtr(">");
        }
        return;
    } else if (xml->name.ptr[0] == '?') {
        WriteStringMap(&xml->attr);
        WriteStrPtr("?>");
        return;
    }

    // 输出元素属性
    WriteStringMap(&xml->attr);
    if (StringIsEmpty(&xml->val)) {
        WriteStrPtr("/>");
        return;
    }
    WriteStrPtr(">");

    // 输出元素内容
    if (xml->hasFreeVal) {
        WriteString(&xml->val);
    } else {
        int i;
        for (i = 0; i < xml->sub.count; i++) {
            WriteXmlItem(xml->sub.list[i], space + 1);
        }
        WriteNewLine(space);
    }

    // 输出结束标签
    WriteStrPtr("</");
    WriteString(&xml->name);
    WriteStrPtr(">");
}